package com.ywjt.platformbusiness.store.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.ywjt.platformbusiness.R;
import com.ywjt.platformbusiness.base.BaseActivity;
import com.ywjt.platformbusiness.base.BaseModel;
import com.ywjt.platformbusiness.constants.Constants;
import com.ywjt.platformbusiness.constants.UrlConstants;
import com.ywjt.platformbusiness.http.HttpRequest;
import com.ywjt.platformbusiness.http.HttpStringCallBack;
import com.ywjt.platformbusiness.store.adapter.UpGoodsFragmentAdapter;
import com.ywjt.platformbusiness.store.model.StoreGoodsListModel;
import com.ywjt.platformbusiness.util.JsonUtils;
import com.ywjt.platformbusiness.util.WarningDialog;
import com.ywjt.platformbusiness.widget.CenterDialogPriceModify;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class StoreGoodsTypeActivity extends BaseActivity implements View.OnClickListener {
    private RecyclerView rcGoods;
    private TextView tvDownGodds,tvUpOrDelGodds,tvEditGoods;
    private ImageView ivSelectAll;
    private LinearLayout llDownGoods;
    private SmartRefreshLayout refresh;
    private LinearLayout llNodata;
    private UpGoodsFragmentAdapter goodsAdapter;
    private List<StoreGoodsListModel.ResultDTO.RecordsDTO> data;
    private PopupWindow popupWindow;

    private Integer currentPage=1;
    private int count=0;
    private String typeId="";
    private int type=0;
    private Boolean isSelectAll=false;
    private int delOrUp=0;//1 全部上架 2全部删除

    public static void actionStart(Context context,Integer type,String typeId) {
        Intent intent = new Intent(context, StoreGoodsTypeActivity.class);
        intent.putExtra("type",type);
        intent.putExtra("typeId",typeId);
        context.startActivity(intent);
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        setAndroidNativeLightStatusBar(true);
    }

    @Override
    protected int setLayoutResourceID() {
        return R.layout.activity_store_goods_type;
    }

    @Override
    protected void initView() {
        setTitleText("商品分类");
        typeId=getIntent().getStringExtra("typeId");
        type=getIntent().getIntExtra("type",0);
        rcGoods=findViewById(R.id.rcCommon);
        llNodata=findViewById(R.id.llNodata);
        refresh=findViewById(R.id.refresh);
        llDownGoods=findViewById(R.id.llDownGoods);
        tvEditGoods=findViewById(R.id.tvEditGoods);
        ivSelectAll=findViewById(R.id.ivSelectAll);
        tvUpOrDelGodds=findViewById(R.id.tvUpOrDelGodds);
        tvDownGodds=findViewById(R.id.tvDownGodds);
        tvDownGodds.setOnClickListener(this::onClick);
        ivSelectAll.setOnClickListener(this);
        tvUpOrDelGodds.setOnClickListener(this::onClick);
        tvEditGoods.setOnClickListener(this::onClick);

        if (type==0){
            llDownGoods.setVisibility(View.GONE);
            tvDownGodds.setVisibility(View.VISIBLE);
            tvUpOrDelGodds.setVisibility(View.GONE);
        }else {
            llDownGoods.setVisibility(View.VISIBLE);
            tvDownGodds.setVisibility(View.GONE);
            tvUpOrDelGodds.setVisibility(View.VISIBLE);
        }
        setView();
        getData();
    }

    @Override
    protected void initData() { }

    /**
     * 获取要使用的标题栏样式(此函数由子类重写)
     * @return
     */
    @Override
    protected int getTitleBarType() {
        return 0;
    }


    //获取数据
    public void getData(){
        Map map = new HashMap<>();
        map.put("categoryId",typeId);
        map.put("pageNo", String.valueOf(currentPage));
        map.put("pageSize", String.valueOf(Constants.PAGESIZE));
        map.put("status",String.valueOf(type));

        new HttpRequest(this).doGet(UrlConstants.commodity_getPutAwayOrSoldOutList, "", map, new HttpStringCallBack() {
            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onSuccess(Object result) {
                String datas = result.toString();
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(datas);
                    String message = jsonObject.getString("message");
                    Boolean success = jsonObject.getBoolean("success");
                    if (success) {
                        Object obj = JsonUtils.fromJson(result.toString(), StoreGoodsListModel.class);
                        if (obj instanceof StoreGoodsListModel) {
                            StoreGoodsListModel model=(StoreGoodsListModel)obj;
                            if (currentPage == 1) {
                                data.clear();
                                count = model.getResult().getTotal();
                                if (model.getResult().getRecords().size() > 0) {
                                    llNodata.setVisibility(View.GONE);
                                    rcGoods.setVisibility(View.VISIBLE);
                                    data=model.getResult().getRecords();
                                    goodsAdapter=new UpGoodsFragmentAdapter(data);
                                    rcGoods.setLayoutManager(new GridLayoutManager(StoreGoodsTypeActivity.this,2,RecyclerView.VERTICAL,false));
                                    rcGoods.setAdapter(goodsAdapter);
                                    if (goodsAdapter.getItemCount() < count) {
                                        //还有多的数据
                                        refresh.finishRefresh();
                                    } else {
                                        //没有更多数据（上拉加载功能将显示没有更多数据）
                                        refresh.finishRefreshWithNoMoreData();
                                    }
                                    goodsAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                                        @Override
                                        public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                                            // ActivityfeedBackDetail.actionStart(context,data.get(position).getId(),type);
                                        }
                                    }) ;
                                    goodsAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
                                        @Override
                                        public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                                            if (type==0){
                                                switch (view.getId()){
                                                    case R.id.ivMore:
                                                        //更多 弹出来弹窗
                                                        View inflate = LayoutInflater.from(getContext()).inflate(R.layout.popu_down_goods,null);
                                                        LinearLayout llDownGoods=inflate.findViewById(R.id.llDownGoods);
                                                        LinearLayout llEditPrice=inflate.findViewById(R.id.llEditPrice);
                                                        llEditPrice.setVisibility(View.GONE);
                                                        llDownGoods.setOnClickListener(new View.OnClickListener() {
                                                            @Override
                                                            public void onClick(View v) {
                                                                WarningDialog dialog=new WarningDialog(StoreGoodsTypeActivity.this,"确认下架商品吗？","取消","确认","提示");
                                                                dialog.setClicklistener(new WarningDialog.ClickListenerInterface() {
                                                                    @Override
                                                                    public void doCancel() {
                                                                        dialog.dismiss();
                                                                    }

                                                                    @Override
                                                                    public void doConfirm() {
                                                                        dialog.dismiss();
                                                                        upOrDownGoods(data.get(position).getId());
                                                                        popupWindow.dismiss();
                                                                    }
                                                                });
                                                                dialog.show();
                                                            }
                                                        });
                                                        popupWindow = new PopupWindow(inflate, RelativeLayout.LayoutParams.WRAP_CONTENT,
                                                                RelativeLayout.LayoutParams.WRAP_CONTENT);
                                                        //设置背景,这个没什么效果，不添加会报错
                                                        popupWindow.setBackgroundDrawable(new BitmapDrawable());
                                                        //设置点击弹窗外隐藏自身
                                                        popupWindow.setFocusable(true);
                                                        popupWindow.setOutsideTouchable(true);
                                                        //相对于某一个控件的位置
                                                        popupWindow.showAsDropDown(view,-100,-240);
                                                        break;
                                                }
                                            }else {
                                                switch (view.getId()){
                                                    case R.id.ivMore:
                                                        //更多 弹出来弹窗
                                                        View inflate = LayoutInflater.from(getContext()).inflate(R.layout.popu_up_goods,null);
                                                        LinearLayout llUpGoods=inflate.findViewById(R.id.llUpGoods);
                                                        LinearLayout llEditPrice=inflate.findViewById(R.id.llEditPrice);
                                                        LinearLayout llDelete=inflate.findViewById(R.id.llDelete);
                                                        llEditPrice.setVisibility(View.GONE);
                                                        llDelete.setOnClickListener(new View.OnClickListener() {
                                                            @Override
                                                            public void onClick(View v) {
                                                                WarningDialog dialog=new WarningDialog(StoreGoodsTypeActivity.this,"确认删除商品吗？","取消","确认","提示");
                                                                dialog.setClicklistener(new WarningDialog.ClickListenerInterface() {
                                                                    @Override
                                                                    public void doCancel() {
                                                                        dialog.dismiss();
                                                                    }

                                                                    @Override
                                                                    public void doConfirm() {
                                                                        dialog.dismiss();
                                                                        deleteGoods(data.get(position).getId());
                                                                        popupWindow.dismiss();

                                                                    }
                                                                });
                                                                dialog.show();
                                                            }
                                                        });
                                                        llUpGoods.setOnClickListener(new View.OnClickListener() {
                                                            @Override
                                                            public void onClick(View v) {
                                                                WarningDialog dialog=new WarningDialog(StoreGoodsTypeActivity.this,"确认上架商品吗？","取消","确认","提示");
                                                                dialog.setClicklistener(new WarningDialog.ClickListenerInterface() {
                                                                    @Override
                                                                    public void doCancel() {
                                                                        dialog.dismiss();
                                                                    }

                                                                    @Override
                                                                    public void doConfirm() {
                                                                        dialog.dismiss();
                                                                        upOrDownGoods(data.get(position).getId());
                                                                        popupWindow.dismiss();
                                                                    }
                                                                });
                                                                dialog.show();
                                                            }
                                                        });

                                                        popupWindow = new PopupWindow(inflate, RelativeLayout.LayoutParams.WRAP_CONTENT,
                                                                RelativeLayout.LayoutParams.WRAP_CONTENT);
                                                        //设置背景,这个没什么效果，不添加会报错
                                                        popupWindow.setBackgroundDrawable(new BitmapDrawable());
                                                        //设置点击弹窗外隐藏自身
                                                        popupWindow.setFocusable(true);
                                                        popupWindow.setOutsideTouchable(true);
                                                        //相对于某一个控件的位置
                                                        popupWindow.showAsDropDown(view,-100,-240);
                                                        break;
                                                }
                                            }
                                        }
                                    });
                                } else {
                                    rcGoods.setVisibility(View.GONE);
                                    refresh.finishRefreshWithNoMoreData();
                                    llNodata.setVisibility(View.VISIBLE);
                                }
                            } else {
                                data.addAll(model.getResult().getRecords());
                                goodsAdapter.notifyDataSetChanged();
                                if (goodsAdapter.getItemCount() < count) {
                                    //还有多的数据
                                    refresh.finishLoadMore();
                                } else {
                                    //没有更多数据（上拉加载功能将显示没有更多数据）
                                    refresh.finishLoadMoreWithNoMoreData();//将不会再次触发加载更多事件
                                }
                            }
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int code, String msg) {
                refresh.finishRefresh();
                refresh.finishLoadMore();
            }
        });
    }


    public void setView(){
        data=new ArrayList<>();
        refresh.setEnableAutoLoadMore(true);//开启自动加载功能（非必须）
        refresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(final RefreshLayout refreshLayout) {
                refreshLayout.getLayout().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        currentPage = 1;
                        getData();
                    }
                }, 1000);
            }
        });
        refresh.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull final RefreshLayout refreshLayout) {
                refreshLayout.getLayout().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        currentPage++;
                        getData();
                    }
                }, 1000);
            }
        });
    }

    /**
     * Called when a view has been clicked.
     *
     * @param v The view that was clicked.
     */
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.tvEditGoods:
                //编辑商品
                View inflate = LayoutInflater.from(getContext()).inflate(R.layout.popu_top_msg,null);
                TextView tvAllDel=inflate.findViewById(R.id.tvAllDel);
                TextView tvAllUp=inflate.findViewById(R.id.tvAllUp);
                tvAllUp.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                            //全部上架
                        delOrUp=1;
                        tvUpOrDelGodds.setText("上架");
                        popupWindow.dismiss();
                    }
                });
                tvAllDel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //全部删除
                        delOrUp=2;
                        tvUpOrDelGodds.setText("删除");
                        popupWindow.dismiss();
                    }
                });
                popupWindow = new PopupWindow(inflate, RelativeLayout.LayoutParams.WRAP_CONTENT,
                        RelativeLayout.LayoutParams.WRAP_CONTENT);
                //设置背景,这个没什么效果，不添加会报错
                popupWindow.setBackgroundDrawable(new BitmapDrawable());
                //设置点击弹窗外隐藏自身
                popupWindow.setFocusable(true);
                popupWindow.setOutsideTouchable(true);
                //相对于某一个控件的位置
                popupWindow.showAsDropDown(tvEditGoods,0,0);
                break;
            case R.id.ivSelectAll:
                //全选
                if (isSelectAll){
                    //已经全选了
                    ivSelectAll.setImageResource(R.mipmap.icon_cart_child_unselected);
                }else {
                    //没有全选
                    ivSelectAll.setImageResource(R.mipmap.icon_cart_child_selected);
                }
                isSelectAll=!isSelectAll;
                break;
            case R.id.tvDownGodds:
                //下架
                if (isSelectAll){
                    //调用全选下架接口
                    upOrDownAllGoods();
                }else {
                    Toast.makeText(StoreGoodsTypeActivity.this,"请先选择需要下架的商品",Toast.LENGTH_SHORT).show();
                    return;
                }
                break;
            case R.id.tvUpOrDelGodds:
                if (isSelectAll){
                    //调用全选下架接口
                    if (delOrUp==0){
                        Toast.makeText(StoreGoodsTypeActivity.this,"请先选择上架或者删除",Toast.LENGTH_SHORT).show();
                        return;
                    }else if(delOrUp==1){
                        upOrDownAllGoods();
                    }else if (delOrUp==2){
                        deleteAllGoods();
                    }
                }else {
                    Toast.makeText(StoreGoodsTypeActivity.this,"请先选择需要上架或删除的商品",Toast.LENGTH_SHORT).show();
                    return;
                }
                break;
        }
    }

    //上架/下架商品
    public void upOrDownGoods(String  id){
        new HttpRequest(getContext()).doPost(UrlConstants.commodity_modifyCommodityStatus+id, "", new HttpStringCallBack() {
            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onSuccess(Object result) {

                String data = result.toString();
                //把请求得数据转换成json对象
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(data);
                    String message = jsonObject.getString("message");
                    Boolean success=jsonObject.getBoolean("success");
                    if(success){
                        Object obj = JsonUtils.fromJson(result.toString(), BaseModel.class);
                        if (obj instanceof BaseModel) {
                            BaseModel model = (BaseModel) obj;
                            getData();
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int code, String msg) {
            }
        });
    }


    //上架/下架全选商品
    public void upOrDownAllGoods(){
        new HttpRequest(getContext()).doPost(UrlConstants.commodity_modifyAllCommodityStatus+(type==0?"1":"0"), "", new HttpStringCallBack() {
            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onSuccess(Object result) {

                String data = result.toString();
                //把请求得数据转换成json对象
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(data);
                    String message = jsonObject.getString("message");
                    Boolean success=jsonObject.getBoolean("success");
                    if(success){
                        Object obj = JsonUtils.fromJson(result.toString(), BaseModel.class);
                        if (obj instanceof BaseModel) {
                            BaseModel model = (BaseModel) obj;
                            getData();
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int code, String msg) {
            }
        });
    }

    //删除商品
    public void deleteGoods(String  id){
        new HttpRequest(getContext()).doPost(UrlConstants.commodity_deleteCommodity+id, "", new HttpStringCallBack() {
            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onSuccess(Object result) {

                String data = result.toString();
                //把请求得数据转换成json对象
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(data);
                    String message = jsonObject.getString("message");
                    Boolean success=jsonObject.getBoolean("success");
                    if(success){
                        Object obj = JsonUtils.fromJson(result.toString(), BaseModel.class);
                        if (obj instanceof BaseModel) {
                            BaseModel model = (BaseModel) obj;
                            getData();
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int code, String msg) {
            }
        });
    }

    //删除全选下架商品
    public void deleteAllGoods(){
        new HttpRequest(getContext()).doPost(UrlConstants.commodity_deleteAllCommodityBySold, "", new HttpStringCallBack() {
            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onSuccess(Object result) {

                String data = result.toString();
                //把请求得数据转换成json对象
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(data);
                    String message = jsonObject.getString("message");
                    Boolean success=jsonObject.getBoolean("success");
                    if(success){
                        Object obj = JsonUtils.fromJson(result.toString(), BaseModel.class);
                        if (obj instanceof BaseModel) {
                            BaseModel model = (BaseModel) obj;
                            getData();
                        }
                    }else {
                        Toast.makeText(StoreGoodsTypeActivity.this,message,Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int code, String msg) {
            }
        });
    }

}